#include "userdao.h"
#include <QSqlQuery>
#include <QDebug>

UserDao *UserDao::instance = nullptr;


bool UserDao::insertUser(UserEnity ue, bool &ok)
{
    QSqlQuery query;

    //是否有重复的用户名存入过数据库
    query.prepare("select * from user where username = ?");//查找是否有重复的用户名
    query.bindValue(0,ue.username);
    bool exeok = query.exec();
    if(query.next())
    {
        ok = false;
        return exeok;
    }

    query.prepare("insert into user(username, password) values(?,?)");
    query.bindValue(0,ue.username);
    query.bindValue(1,ue.password);
    exeok = query.exec();
    ok = true;
    return exeok;
}

bool UserDao::selectUser(UserEnity ue, bool &ok)
{
    QSqlQuery query;
    query.prepare("select * from user where username = ? and password = ?");
    query.bindValue(0,ue.username);
    query.bindValue(1,ue.password);
    bool exeok = query.exec();//数据库执行语句是否成功
    ok = query.next();//是否查询到对应的账户名和密码
    return exeok;
}

UserDao *UserDao::getInstance()
{
    if(instance == nullptr)
    {
        instance = new UserDao();
    }
    return instance;
}

void UserDao::releaseInstance()
{
    if(instance != nullptr)
    {
        delete instance;
        instance = nullptr;
    }
}

UserDao::UserDao()
{
    db = QSqlDatabase::addDatabase("QSQLITE");
    db.setHostName("userdb");//主机名
    db.setDatabaseName("userdb.db");//数据库文件名
    db.open();

    QSqlQuery query;
    bool ok = query.exec("create table if not exists user("
                         "id integer primary key autoincrement,"
                         "username char(20),"
                         "password char(20)"
                         ")");
    qDebug()<<ok;
}

UserDao::~UserDao()
{

}

UserDao::UserDao(const UserDao &other)
{

}
